import { Navigate, useRoutes } from "react-router-dom";
import KeepAlive from "react-activation";
import { RouteObject } from "./interface";
import Login from "@/pages/login/login";

// 导入所有router
const metaRouters = import.meta.glob("./modules/*.tsx", { eager: true });

// 处理路由
export const routerArray: RouteObject[] = [];
Object.keys(metaRouters).forEach(item => {
	Object.keys(metaRouters[item]).forEach((key: any) => {
		routerArray.push(...metaRouters[item][key]);
	});
});

export const rootRouter: RouteObject[] = [
	{
		path: "/",
		element: <Navigate to="/login" />
	},
	{
		path: "/login",
		element: <Login />,
		meta: {
			title: "登录页",
			key: "login"
		}
	},
	...routerArray,
	{
		path: "*",
		element: <Navigate to="/404" />
	}
];

const generateRouter = (routers: any) => {
	let newRouters: any = {};
	return routers.map((item: any) => {
		newRouters = {
			path: item.path,
			element: <KeepAlive id={item.path}>{item.element}</KeepAlive>
			// element: item.element
		};
		if (item.children) {
			newRouters.children = generateRouter(item.children);
		}
		return newRouters;
	});
};

const Router = () => {
	const elementRoute = useRoutes(generateRouter(rootRouter));
	return elementRoute;
};
export default Router;
